package com.captjack.common.util.dynamicproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author Capt Jack
 * @date 2018/7/23
 */
public class DynamicProxyHandler implements InvocationHandler {

    /**
     * 需要代理的对象
     */
    private Object proxy;

    /**
     * 动态生成方法被处理过后的对象
     *
     * @param proxy 元对象
     * @return 代理后的对象
     */
    public Object proxy(Object proxy) {
        this.proxy = proxy;
        return Proxy.newProxyInstance(this.proxy.getClass().getClassLoader(), this.proxy.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = null;
        try {
            System.out.println("start");
            result = method.invoke(this.proxy, args);
            System.out.println("end");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
